import json
from db import models
import asyncio

class Get_Rag_db:
    async def run(self, *args, **kwargs):
        data = await models.Rag_db.all().values()
        result = [{"description": rag.get('description'), "rag_path": rag.get('rag_path'), "chunks": json.loads(rag.get('chunks'))} for rag in data]
        return result

async def get_rag_db_async(*args, **kwargs):
    instance = Get_Rag_db()
    return await instance.run(**kwargs)

def get_rag_db_sync(*args, **kwargs):
    try:
        loop = asyncio.get_event_loop()
        if loop.is_running():
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            result = loop.run_until_complete(Get_Rag_db().run(**kwargs))
            loop.close()
            return result
        else:
            return loop.run_until_complete(Get_Rag_db().run(**kwargs))
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(Get_Rag_db().run(**kwargs))
        loop.close()
        return result